import historyComponent from './components/history.vue';
export default {
    install (app,options) {
        const optionsInt = {
            persist: false,
            key: 'name'
        };
        options = Object.assign(optionsInt, options);
        let router = app.config.globalProperties.$router;
        const remove = (index) => { 
            let history = app.config.globalProperties.$history
            history.list.splice(index, 1) 
            app.config.globalProperties.$history.list = history.list
            if (options && options.persist) {
                localStorage.setItem('history', JSON.stringify(history.list));
            }
        }
        let history = app.config.globalProperties.$history || {
            list: [],
            remove: remove,
            clear: () => { 
                history.list = []; 
                app.config.globalProperties.$history = history
                if (options && options.persist) {
                    localStorage.setItem('history', JSON.stringify(history.list));
                }
            }
        };
        

        if (options && options.persist) {
            history.list = JSON.parse(localStorage.getItem('history')) || history.list || [];
        }
        router.beforeEach((to, from) => {
            
            if (from) {
                let hasIndex = history.list.findIndex(item => item[options.key] === from[options.key]) 
                if (hasIndex >= 0) history.list[hasIndex] = from;
                if (hasIndex < 0) history.list.push(from);
                app.config.globalProperties.$history = history;
                if (options && options.persist) {
                    localStorage.setItem('history', JSON.stringify(history.list));
                }
            }
        });
        
        app.component('History', historyComponent)
        
    }
}